'use strict';
const db = uniCloud.database();

/**
 * 检查指定订单的日期信息
 * 用于诊断激活日期和倒计时问题
 */
exports.main = async (event, context) => {
  const { orderIds } = event;
  
  console.log('========================================');
  console.log('开始检查订单日期信息...');
  console.log('========================================');
  
  try {
    // 如果没有指定订单ID，查询所有待激活的订单
    let query = {};
    if (orderIds && Array.isArray(orderIds) && orderIds.length > 0) {
      query._id = db.command.in(orderIds);
    } else {
      // 查询所有待激活的订单
      query.commission_status = 'pending';
      query.status = 'completed';
    }
    
    const ordersRes = await db.collection('orders')
      .where(query)
      .field({
        _id: true,
        status: true,
        create_time: true,
        completed_time: true,
        activation_date: true,
        activation_countdown: true,
        commission_status: true,
        commission_amount: true,
        promoter_id: true,
        amount: true
      })
      .orderBy('completed_time', 'desc')
      .limit(50)
      .get();
    
    if (ordersRes.data.length === 0) {
      console.log('没有找到符合条件的订单');
      return {
        success: true,
        count: 0,
        message: '没有找到符合条件的订单'
      };
    }
    
    console.log(`\n找到 ${ordersRes.data.length} 条订单\n`);
    
    const now = Date.now();
    const results = [];
    
    for (const order of ordersRes.data) {
      console.log(`\n========== 订单 ${order._id} ==========`);
      console.log(`订单状态: ${order.status}`);
      console.log(`订单金额: ¥${(order.amount / 100).toFixed(2)}`);
      console.log(`返利金额: ¥${(order.commission_amount / 100).toFixed(2)}`);
      console.log(`返利状态: ${order.commission_status}`);
      console.log(`推荐人ID: ${order.promoter_id || '无'}`);
      
      // 创建时间
      if (order.create_time) {
        const createDate = new Date(order.create_time);
        console.log(`\n创建时间: ${createDate.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}`);
        console.log(`创建时间戳: ${order.create_time}`);
      } else {
        console.log(`\n创建时间: 未记录`);
      }
      
      // 完成时间
      if (order.completed_time) {
        const completedDate = new Date(order.completed_time);
        console.log(`\n完成时间: ${completedDate.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}`);
        console.log(`完成时间戳: ${order.completed_time}`);
        
        // 计算距离完成已经过去多少天
        const daysSinceCompleted = Math.floor((now - order.completed_time) / (24 * 60 * 60 * 1000));
        console.log(`距离完成: ${daysSinceCompleted} 天`);
      } else {
        console.log(`\n完成时间: 未记录 ❌`);
      }
      
      // 激活日期
      if (order.activation_date) {
        const activationDate = new Date(order.activation_date);
        console.log(`\n激活日期: ${activationDate.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}`);
        console.log(`激活日期戳: ${order.activation_date}`);
        
        // 检查激活日期是否已到
        const isActivationDateReached = now >= order.activation_date;
        console.log(`激活日期已到: ${isActivationDateReached ? '✅ 是' : '❌ 否'}`);
        
        if (!isActivationDateReached) {
          const daysUntilActivation = Math.ceil((order.activation_date - now) / (24 * 60 * 60 * 1000));
          console.log(`距离激活: ${daysUntilActivation} 天`);
        } else {
          const daysOverdue = Math.floor((now - order.activation_date) / (24 * 60 * 60 * 1000));
          console.log(`⚠️ 激活日期已过 ${daysOverdue} 天，但订单仍未激活！`);
        }
        
        // 验证激活日期是否等于完成时间 + 7天
        if (order.completed_time) {
          const expectedActivationDate = order.completed_time + 7 * 24 * 60 * 60 * 1000;
          const dateDiff = Math.abs(order.activation_date - expectedActivationDate);
          const daysDiff = dateDiff / (24 * 60 * 60 * 1000);
          
          if (daysDiff < 0.1) {
            console.log(`激活日期计算: ✅ 正确（完成时间 + 7天）`);
          } else {
            console.log(`激活日期计算: ❌ 错误`);
            console.log(`  预期激活日期: ${new Date(expectedActivationDate).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}`);
            console.log(`  实际激活日期: ${activationDate.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}`);
            console.log(`  差异: ${daysDiff.toFixed(1)} 天`);
          }
        }
      } else {
        console.log(`\n激活日期: 未记录 ❌`);
      }
      
      // 激活倒计时
      console.log(`\n激活倒计时字段: ${order.activation_countdown}`);
      
      // 汇总结果
      results.push({
        orderId: order._id,
        status: order.status,
        commissionStatus: order.commission_status,
        commissionAmount: order.commission_amount,
        createTime: order.create_time,
        completedTime: order.completed_time,
        activationDate: order.activation_date,
        activationCountdown: order.activation_countdown,
        isActivationDateReached: order.activation_date ? now >= order.activation_date : null,
        daysSinceCompleted: order.completed_time ? Math.floor((now - order.completed_time) / (24 * 60 * 60 * 1000)) : null,
        daysUntilActivation: order.activation_date ? Math.ceil((order.activation_date - now) / (24 * 60 * 60 * 1000)) : null
      });
    }
    
    console.log('\n========================================');
    console.log('检查完成！');
    console.log('========================================');
    
    return {
      success: true,
      count: ordersRes.data.length,
      currentTime: now,
      currentTimeStr: new Date(now).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }),
      results
    };
  } catch (err) {
    console.error('❌ 检查过程发生错误:', err);
    return {
      success: false,
      error: err.message,
      message: '检查过程发生错误'
    };
  }
};

